package com.yupi.yupicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.mapper.SpaceMapper;
import com.yupi.yupicturebackend.model.dto.picture.PictureEditRequest;
import com.yupi.yupicturebackend.model.dto.space.SpaceAddRequest;
import com.yupi.yupicturebackend.model.dto.space.SpaceQueryRequest;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.SpaceLevelEnum;
import com.yupi.yupicturebackend.model.vo.PictureVO;
import com.yupi.yupicturebackend.model.vo.SpaceVO;
import com.yupi.yupicturebackend.model.vo.UserVO;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author Y9000
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-09-23 18:48:46
*/
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space> implements SpaceService {

    @Resource
    private UserService userService;

    @Resource
    private TransactionTemplate transactionTemplate;



    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        // 仅本人或管理员可编辑
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }

    //校验参数
    @Override
    public void validSpace(Space space,boolean add) {
        ThrowUtils.throwIf(space==null, ErrorCode.PARAMS_ERROR);

        //从对象中取值
        String spaceName = space.getSpaceName();
        Integer  spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);

        //要创建
        if(add){
            if(StrUtil.isBlank(spaceName)){
                throw  new BusinessException(ErrorCode.PARAMS_ERROR,"空间名称不能为空");
            }
            if(spaceLevel==null){
                throw  new BusinessException(ErrorCode.PARAMS_ERROR,"空间等级不能为空");
            }
        }

        //修改数据时，如果要改空间级别
        if(spaceLevel!=null &&spaceLevelEnum==null){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"空间等级错误");
        }

        if(StrUtil.isNotBlank(spaceName) && spaceName.length() > 30){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR,"空间名称过长");
        }
    }

    //根据空间等级填充空间信息
    @Override
    public void fillSpaceBySpaceLevel(Space space) {

        //根据空间级别，自动填充限额
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if(spaceLevelEnum!=null){
            long maxSize = spaceLevelEnum.getMaxSize();
            if(space.getMaxSize()== null){
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if(space.getMaxCount()== null){
                space.setMaxCount(maxCount);
            }
        }

    }


    @Override
    public List<String> getPermissionList(Space space, User loginUser) {

        return null;


    }

    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser){

        //在此进行实体类和DTO类进行转换
        Space space = new Space();
        BeanUtil.copyProperties(spaceAddRequest,space);
        //默认值
        if(StrUtil.isBlank(spaceAddRequest.getSpaceName())){
            space.setSpaceName("默认空间");
        }
        if(spaceAddRequest.getSpaceLevel()==null){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        //填充数据
        this.fillSpaceBySpaceLevel(space);
        //数据校验
        this.validSpace(space,true);

        Long userId= loginUser.getId();
        space.setUserId(userId);

        if(SpaceLevelEnum.COMMON.getValue()!= spaceAddRequest.getSpaceLevel()&&!userService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"无权限创建指定级别的空间");
        }

        //针对用户进行加锁
        String lock=String.valueOf(userId).intern();
        synchronized ( lock){
            Long spaceId =  transactionTemplate.execute(transactionStatus -> {
                boolean exists=this.lambdaQuery()
                        .eq(Space::getUserId,userId)
                        .exists();
                ThrowUtils.throwIf(exists,ErrorCode.OPERATION_ERROR,"用户已存在空间");
                //插入数据库
                boolean result=   this.save( space);
                ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
                return space.getId();

            });
            return Optional.ofNullable(spaceId).orElse(-1L);
        }







    }

//    //编辑图片
//    @Override
//    public  void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
//
//        Picture picture = new Picture();
//        BeanUtil.copyProperties(pictureEditRequest,picture);
//        //注意list转为string
//        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
//        //设置编辑时间
//        picture.setEditTime(new Date());
//        //数据校验
//        this.validPicture(picture);
//        this.checkSpaceAuth(loginUser,picture);
//    }




    //获取查询条件
    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Integer spaceType = spaceQueryRequest.getSpaceType();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        // 拼接查询条件
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        
        return queryWrapper;
    }

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {

        // 对象转封装类
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        // 关联查询用户信息
        Long userId = space.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            spaceVO.setUser(userVO);
        }
        return spaceVO;

    }

//    @Override
//    public List<String> getPermissionList( String spaceUserRole) {
//
//        if (StrUtil.isBlank(spaceUserRole)) {
//            return new ArrayList<>();
//        }
//        SpaceUserRole role = SPACE_USER_AUTH_CONFIG.getRoles()
//                .stream()
//                .filter(r -> r.getKey().equals(spaceUserRole))
//                .findFirst()
//                .orElse(null);
//        if (role == null) {
//            return new ArrayList<>();
//        }
//        return role.getPermissions();
//        return Collections.emptyList();
//    }


    //获取空间分页
    @Override
    public Page<SpaceVO> getspaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList = spacePage.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(spacePage.getCurrent(), spacePage.getSize(), spacePage.getTotal());
        if (CollUtil.isEmpty(spaceList)) {
            return spaceVOPage;
        }
        // 对象列表 => 封装对象列表
        List<SpaceVO> spaceVOList = spaceList.stream()
                .map(SpaceVO::objToVo)
                .collect(Collectors.toList());
        // 1. 关联查询用户信息
        // 1,2,3,4
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        // 1 => user1, 2 => user2
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        spaceVOList.forEach(spaceVO -> {
            Long userId = spaceVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            spaceVO.setUser(userService.getUserVO(user));
        });
        spaceVOPage.setRecords(spaceVOList);
        return spaceVOPage;

    }
}




